<?php
namespace PFT;
/**
 * Created by PhpStorm.
 * User: Guangpeng Chen
 * Date: 15-1-15
 * Time: 下午3:25
 */
class Db
{
    private static $host = '127.0.0.1';
    private static $username = 'admin';
    private static $pwd = 'adm*753951';
    private static $dbname = 'myuu_test';
    private static $port = 3307;
    private static $con = null;
    private static $conPool = null;

    private function __construct()
    {
    }

    public static function Conf(Array $conf)
    {
        if (!is_null(self::$con)) {
            self::Close();
        }
        self::$host = $conf['host'];
        self::$username = $conf['username'];
        self::$pwd = $conf['pwd'];
        self::$dbname = $conf['dbname'];
        self::$port = $conf['port'];
    }

    public static function Connect($key=null)
    {
        if (!is_null($key)) {
            if (is_null(self::$conPool[$key])) {
                $dsn = "mysql:dbname=" . self::$dbname . ";host=" . self::$host . ";port=" . self::$port;
                $pdo = new \PDO($dsn, self::$username, self::$pwd);
                $pdo->exec('SET NAMES "UTF8"');
                self::$conPool[$key] = $pdo;
                return self::$conPool[$key];
            } else {
                return self::$conPool[$key];
            }
        }
        else {
            if (is_null(self::$con)) {
                $dsn = "mysql:dbname=" . self::$dbname . ";host=" . self::$host . ";port=" . self::$port;
                $pdo = new \PDO($dsn, self::$username, self::$pwd);
                $pdo->exec('SET NAMES "UTF8"');
                self::$con = $pdo;
                return self::$con;
            } else {
                return self::$con;
            }
        }
    }

    public static function &ConnectRef($key=null)
    {
        if (!is_null($key)) {
            if (is_null(self::$conPool[$key])) {
                $dsn = "mysql:dbname=" . self::$dbname . ";host=" . self::$host . ";port=" . self::$port;
                $pdo = new \PDO($dsn, self::$username, self::$pwd);
                $pdo->exec('SET NAMES "UTF8"');
                self::$conPool[$key] = $pdo;
                return self::$conPool[$key];
            } else {
                return self::$conPool[$key];
            }
        }
        else {
            if (is_null(self::$con)) {
                $dsn = "mysql:dbname=" . self::$dbname . ";host=" . self::$host . ";port=" . self::$port;
                $pdo = new \PDO($dsn, self::$username, self::$pwd);
                $pdo->exec('SET NAMES "UTF8"');
                self::$con = $pdo;
                return self::$con;
            } else {
                return self::$con;
            }
        }
    }

    public static function Close($key=null)
    {
        self::$con = null;
        if (!is_null($key)) unset(self::$conPool[$key]);// = null;
    }
    public static function test()
    {
        return self::$con;
    }
    public static function Update(Array $data, $table, $primary_key,
                                  $primary_key_name='id')
    {
        $sql = "UPDATE `$table` SET ";
        $param = array();
        foreach($data as $col=>$val) {
            $sql .= "$col=?,";
            $param[] = $val;
        }
        $sql = rtrim($sql, ',') . " WHERE `$primary_key_name`=? LIMIT 1";
        $param[] = $primary_key;
        try {
            $stmt = self::Connect()->prepare($sql);
            if ($stmt->execute($param) ) {
                return $primary_key;
            }
            return false;
        } catch (\PDOException $e) {
            return $e->getMessage();
        }
    }
    public static function Insert($data, $table)
    {
        $values = array_values($data);
        $question_marks = '(' . placeholders('?', sizeof($data)) . ')';
        $sql = "INSERT INTO `{$table}` (" . implode(",", array_keys($data))
            . ") VALUES " . $question_marks;

//        echo $sql;
//        print_r($values);
        try {
            $stmt = self::Connect()->prepare($sql);
            $stmt->execute($values);
            return self::Connect()->lastInsertId();
        } catch (\PDOException $e) {
            return $e->getMessage();
        }
    }

    public function MulInsert($data, $table)
    {
        $row = 0;
        foreach ($data as $d) {
            $ret = self::Insert($d, $table);
            if ($ret > 0) {
                $row += 1;
            }
        }
        return $row;
    }

    public static function fetchAll($sql, Array $param = array())
    {
        $stmt = self::Connect()->prepare($sql);
        $stmt->execute($param);
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }

    public static function fetch($sql, Array $param = array())
    {
        $stmt = self::Connect()->prepare($sql);
        $stmt->execute($param);
        return $stmt->fetch(\PDO::FETCH_ASSOC);
    }

    // 执行增删改
    public static function execute($sql, Array $param=array()){
        try {
            $stmt = self::Connect()->prepare($sql);
            return $stmt->execute($param);
        } catch(\PDOException $e) {
            return $e->getMessage();
        }

    }
    
    public static function lastInsertId(){
        return self::Connect()->lastInsertId();
    }
}

function placeholders($text, $count = 0, $separator = ",")
{
    $result = array();
    if ($count > 0) {
        for ($x = 0; $x < $count; $x++) {
            $result[] = $text;
        }
    }
    return implode($separator, $result);
}